import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/http_server/adderss.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/baidu_map_model.dart';
import 'package:loxen/utils/color.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/view/address/map_location_widget.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:loxen/widget/my_switch.dart';
import 'package:provider/provider.dart';

class ItemBean {
  String id;

  //默认收货地址
  bool defaultAddress = false;

  //省
  String province;

  //市
  String city;

  //区
  String district;

  //详细地址
  String detailedAddress;

  //名字
  String userName;

  //电话
  String telephone;

  /// 精度
  double latitude;

  /// 纬度
  double longitude;

  String adderssString() {
    return "$province $city $district";
  }

  ItemBean(
      {this.id,
      this.defaultAddress,
      this.province,
      this.city,
      this.district,
      this.detailedAddress,
      this.userName,
      this.telephone,
      this.latitude,
      this.longitude});
}

class NewAddressWidget extends StatelessWidget with AddressMixin {
  final TextEditingController name = TextEditingController();
  final TextEditingController telephone = TextEditingController();
  final ValueNotifier<String> address = ValueNotifier(null);
  final TextEditingController addressInfo = TextEditingController();
  final ValueNotifier<bool> defaultAddress = ValueNotifier(false);
  final bool showDistance;
  final ItemBean bean;
  final ItemBean sendBean = ItemBean();
  final dynamic locationList;

  NewAddressWidget({Key key, this.bean, this.showDistance = false, this.locationList})
      : super(key: key);

  Widget itemEdit(
    String title,
    String hint, {
    controller,
    inputType,
    keyType,
  }) {
    return Padding(
      padding: EdgeInsets.only(top: 20.h, bottom: 20.h),
      child: Row(
        children: [
          Expanded(
            flex: 1,
            child: Text(
              title,
              style: TextStyle(
                fontSize: 28.sp,
                color: Color(0xff333333),
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
          Expanded(
              flex: 3,
              child: TextField(
                keyboardType: keyType,
                controller: controller,
                inputFormatters: inputType,
                style: TextStyle(
                  fontSize: 28.sp,
                  color: Color(0xff333333),
                ),
                maxLines: 1,
                decoration: InputDecoration(
                  hintText: hint,
                  isDense: true,
                  hintStyle: TextStyle(
                    fontSize: 28.sp,
                    color: Color(0xff999999),
                  ),
                  border: InputBorder.none,
                ),
              ))
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (bean != null) {
      name.text = bean.userName;
      telephone.text = bean.telephone;
      address.value = bean.adderssString();
      addressInfo.text = bean.detailedAddress;
      defaultAddress.value = bean.defaultAddress;
      sendBean.province = bean.province;
      sendBean.city = bean.city;
      sendBean.district = bean.district;
      sendBean.latitude = bean.latitude;
      sendBean.longitude = bean.longitude;
    }
    return Scaffold(
      backgroundColor: Theme.of(context).backgroundColor,
      appBar: PreferredSize(
        preferredSize: Size(double.infinity, 96.h),
        child: Container(
          color: Theme.of(context).backgroundColor,
          child: SafeArea(
            child: Column(
              children: [
                Row(
                  children: <Widget>[
                    MySubassembly.getBackIcon(context,
                        color: Theme.of(context).textTheme.subtitle2.color),
                    Expanded(
                      child: Center(
                        child: Text(
                          bean == null
                              ? StringResources.xin_zeng_di_zhi
                              : StringResources.xiu_gai_di_zhi,
                          style: TextStyle(
                              fontSize: 32.sp,
                              fontWeight: FontWeight.w500,
                              color: Theme.of(context).textTheme.subtitle2.color),
                        ),
                      ),
                    ),
                    MySubassembly.getSearchIcon(null, text: Text('')),
                  ],
                ),
                Divider(height: 1.h)
              ],
            ),
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 30.h),
          child: Column(
            children: [
              Card(
                elevation: 5,
                child: Container(
                  child: Padding(
                    padding: EdgeInsets.only(left: 20.w, right: 20.w),
                    child: Column(
                      children: [
                        itemEdit('收货人', '请输入收货人姓名', controller: name),
                        Divider(height: 1),
                        itemEdit(
                          '手机号',
                          '请输入收货人手机号',
                          controller: telephone,
                          keyType: TextInputType.phone,
                          inputType: [
                            FilteringTextInputFormatter.digitsOnly,
                            LengthLimitingTextInputFormatter(11)
                          ],
                        ),
                        Divider(height: 1),
                        Padding(
                          padding: EdgeInsets.only(top: 10.h, bottom: 10.h),
                          child: Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: Text(
                                  '所在地区',
                                  style: TextStyle(
                                    fontSize: 28.sp,
                                    color: Color(0xff333333),
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 3,
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: ValueListenableProvider<String>.value(
                                        value: address,
                                        builder: (context, _) {
                                          String str = context.watch<String>();
                                          return Text(
                                            str ?? '请选择所在地区',
                                            style: TextStyle(
                                              fontSize: 28.sp,
                                              color: str == null
                                                  ? Colours.secondary_text
                                                  : Colours.main_text,
                                            ),
                                          );
                                        },
                                      ),
                                    ),
                                    IconButton(
                                        icon: Image.asset(
                                          'images/location_icon.png',
                                          width: 34.w,
                                          height: 34.w,
                                        ),
                                        onPressed: () {
                                          Navigator.of(context)
                                              .push(MaterialPageRoute(
                                                  builder: (_) => MapLocationWidget(
                                                        locationList: locationList,
                                                        showDistance: showDistance,
                                                      )))
                                              .then((value) {
                                            if (value is Result) {
                                              sendBean.province = value.province;
                                              sendBean.city = value.city;
                                              sendBean.district = value.district;
                                              sendBean.latitude = value.location.lat;
                                              sendBean.longitude = value.location.lng;
                                              address.value = sendBean.adderssString();
                                              addressInfo.text = value.name;
                                            }
                                          });
                                        }),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        Divider(height: 1),
                        Padding(
                          padding: EdgeInsets.only(top: 20.h, bottom: 100.h),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(
                                flex: 1,
                                child: Padding(
                                  padding: EdgeInsets.only(top: 15.h),
                                  child: Text(
                                    '详细地址',
                                    style: TextStyle(
                                      fontSize: 28.sp,
                                      color: Color(0xff333333),
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                              ),
                              Expanded(
                                flex: 3,
                                child: TextField(
                                  keyboardType: TextInputType.multiline,
                                  minLines: 1,
                                  maxLines: 10,
                                  controller: addressInfo,
                                  decoration: InputDecoration(
                                    hintText: '请填写详细地址，如：街道楼牌号等',
                                    hintStyle: TextStyle(
                                      fontSize: 28.sp,
                                      color: Color(0xff999999),
                                    ),
                                    border: InputBorder.none,
                                    isDense: true,
                                  ),
                                  style: TextStyle(color: Color(0xff333333), fontSize: 28.sp),
                                ),
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 16.h),
                child: Card(
                  elevation: 5,
                  child: Container(
                    child: Padding(
                      padding: EdgeInsets.only(left: 20.w, right: 20.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(
                            padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
                            child: Row(
                              children: [
                                Expanded(
                                  child: Text(
                                    '默认收货地址',
                                    style: TextStyle(
                                        color: Colours.main_text,
                                        fontSize: 28.sp,
                                        fontWeight: FontWeight.bold),
                                  ),
                                ),
                                ValueListenableProvider<bool>.value(
                                  value: defaultAddress,
                                  builder: (context, _) {
                                    return SizedBox(
                                      width: 72.w,
                                      height: 40.w,
                                      child: MySwitch(
                                          activeColor: Colours.app_main,
                                          value: context.watch<bool>(),
                                          onChanged: (value) {
                                            defaultAddress.value = value;
                                          }),
                                    );
                                  },
                                )
                              ],
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(bottom: 30.h),
                            child: Text(
                              '提示：每次下单会默认推荐使用该地址',
                              style: TextStyle(
                                fontSize: 22.sp,
                                color: Colours.red,
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                width: double.infinity,
                height: 90.h,
                margin: EdgeInsets.only(top: 160.h),
                child: FlatButton(
                    onPressed: () {
                      String name = this.name.text.trim();
                      if (name == '') {
                        return Toast.show('收件人不能为空！', context);
                      }
                      String telephone = this.telephone.text.trim();
                      if (telephone == '') {
                        return Toast.show('手机号不能为空', context);
                      }
                      if (address.value == null) {
                        return Toast.show("请选择所在地区", context);
                      }
                      String addressInfo = this.addressInfo.text.trim();
                      if (addressInfo == '') {
                        return Toast.show('详细地址不能为空', context);
                      }
                      createOrUpdataAddress(
                              name,
                              telephone,
                              sendBean.province,
                              sendBean.city,
                              sendBean.district,
                              addressInfo,
                              defaultAddress.value,
                              sendBean.latitude.toString(),
                              sendBean.longitude.toString(),
                              updata: bean != null,
                              id: bean?.id)
                          .listen((event) {
                        if (event == 200 || event == 201) Navigator.pop(context, true);
                      }, onError: (error, stack) {
                        Toast.show('网络异常！', context);
                        print(stack);
                      });
                    },
                    disabledColor: Colors.grey,
                    color: Color(0xFF0CACCC),
                    child: Text(
                      '保存',
                      style: TextStyle(
                        fontSize: 32.sp,
                        color: Colors.white,
                      ),
                    )),
              ),
              bean != null
                  ? Container(
                      width: double.infinity,
                      height: 90.h,
                      margin: EdgeInsets.only(top: 50.h),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Color(0xffb7b7b7),
                          width: 1.w,
                        ),
                      ),
                      child: FlatButton(
                          onPressed: () {
                            deleteAddress(bean.id).listen((event) {
                              if (event == 200) {
                                Navigator.of(context).pop(true);
                              } else {
                                Toast.show('删除失败', context);
                              }
                            }, onError: (error, stack) {
                              Toast.show('网络异常', context);
                              print(error);
                              print(stack);
                            });
                          },
                          disabledColor: Colors.grey,
                          color: Colours.bg_color,
                          child: Text(
                            '删除',
                            style: TextStyle(
                              fontSize: 32.sp,
                              color: Colours.dark_text_gray,
                            ),
                          )),
                    )
                  : Constants.empty,
              Container(
                height: 120.h,
              )
            ],
          ),
        ),
      ),
    );
  }
}
